import axios from 'axios'
import { Message } from 'element-ui'
import glo_loading from '@/config/glo_loading' //loading组件的简单封装
import { apiLoading } from '@/config/loadingConfig' //全局的页面跳转loading是否启用
import store from '@/store/index.js'
const baseURL =  require('../../base.config.js') 
console.log(baseURL,'baseUrl')
// 创建 axios 实例
const service = axios.create({
  baseURL,
  timeout: 50000, // request timeout 5秒超时
})
let reqNum = 0;
//  请求拦截器
service.interceptors.request.use(

  (config) => {
    // 在请求发出之前进行一些操作，每次发出请求就对设置了loading的请求 reqNum++
    if (apiLoading && config.loading) {
      glo_loading.loadingShow();
      reqNum++
      console.log('开启了' + reqNum + '个设置了loading的请求')
    }
    // console.log(config,"config")
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    config.headers['Accept'] = 'application/json'
    config.headers['client_id'] = 'webApp' // 应用id
    config.headers['client_secret'] = '8e82359e58c871d942e2e4c490db368f' // 应用密钥

    // config.headers['Request-From'] = 'mobile'
    let token = sessionStorage.getItem('loginToken') || null
    if (token) {
      // 如果token不为null，否则传token给后台 
      // config.headers['Authorization'] = token
      config.headers['access_token'] = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {

    // 避免未开启loading的请求关闭正在请求的loading
    let ld = response.config.loading;
    if (apiLoading && ld) {
      // 接受请求后 reqNum--，判断所有设置了loading的请求是否完成
      reqNum--
      console.log('关闭了1个设置了loading的请求，还剩' + reqNum + '个')
      if (reqNum <= 0) {
        // 如果全部完成，半秒后结束loading
        setTimeout(() => {
          console.log('所有请求loading已关闭')
          glo_loading.loadingHide()//关闭loading层
        }, 500)
      } else {
        glo_loading.loadingShow()
      }

    }



    const res = response
    //届时根据后端返回success或者code值判断
    if (res.success === true) {
      return res
    } else {
      return res
    }

  },
  (error) => {
    // console.log(error.response,"error")
    // 避免未开启loading的请求关闭正在请求的loading
    let ld = error.response.config.loading;
    if (apiLoading && ld) {
      // 请求失败后 reqNum--，判断所有设置了loading的请求是否完成
      reqNum--
      console.log('关闭了1个设置了loading的请求，还剩' + reqNum + '个')
      if (reqNum <= 0) {
        // 如果全部完成，直接结束loading
        glo_loading.loadingHide()//关闭loading层
        console.log('所有请求loading已关闭')
      } else {
        glo_loading.loadingShow()
      }
    }

    // 处理错误信息
    let errInfo = "";
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          errInfo = '错误请求';
          break;
        case 401:
          errInfo = '未授权，请重新登录';
          setTimeout(() => { // token失效调用登出
            store.dispatch('logOut')
          }, 2000);
          break;
        case 403:
          errInfo = '拒绝访问';
          break;
        case 404:
          errInfo = '请求错误,未找到该资源';
          break;
        case 405:
          errInfo = '请求方法未允许';
          break;
        case 408:
          errInfo = '请求超时';
          break;
        case 500:
          errInfo = '服务器端出错';
          break;
        case 501:
          errInfo = '网络未实现';
          break;
        case 502:
          errInfo = '网络错误';
          break;
        case 503:
          errInfo = '服务不可用';
          break;
        case 504:
          errInfo = '网络超时';
          break;
        case 505:
          errInfo = 'http版本不支持该请求';
          break;
        default:
          errInfo = `未知错误${error.response.status}`;
      }
    } else {
      errInfo = "连接到服务器失败";
    }
    return Message({
      // 后台返回错误信息中没有中文则显示自定义错误处理信息，包含中文则显示后台返回信息。
      message: (escape(error.response.data.msg).indexOf("%u") < 0) ? errInfo : error.response.data.msg,
      type: 'error',
    });
  }
);
/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 *  loading:请求启动是否loading遮罩
 * */
export function get(url, params = {}, loading = true) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'get',
      params: params,
      loading: loading
    }).then(response => {
      resolve(response.data);
    }).catch(error => {
      reject(error);
    });
  });
}

/*
*  post请求
*  url:请求地址
*  params:参数
*  loading:请求启动是否loading遮罩
* */
export function post(url, params = {}, loading = true) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'post',
      data: params,
      loading: loading
    }).then(response => {
      resolve(response.data);
    }).catch(error => {
      reject(error);
    });
  });
}
export function put(url, params = {}, loading = true) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'put',
      data: params,
      loading: loading
    }).then(response => {
      resolve(response.data);
    }).catch(error => {
      reject(error);
    });
  });
}

export function delet(url, params = {}, loading = false) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'delete',
      params: params || {},
      loading: loading
    }).then(response => {
      resolve(response.data);
    }).catch(error => {
      reject(error);
    });
  });
}

/*
*  文件上传
*  url:请求地址
*  params:参数
*  loading:请求启动是否loading遮罩
* */
export function fileUpload(url, params = {}, loading = true) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'post',
      data: params,
      loading: loading,
      headers: { 'Content-Type': 'multipart/form-data' }
    }).then(response => {
      resolve(response.data);
    }).catch(error => {
      reject(error);
    });
  });
}

/*
*  json格式请求文件流导出excel文件
*  url:请求地址
*  params:参数
*  loading:请求启动是否loading遮罩
//application/octet-stream
* */
export function exportFile(url, params, loading = true) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'post',
      data: params,
      loading: loading,
      headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      responseType: 'arraybuffer'
    }).then(response => {
      resolve(response);
    }).catch(error => {
      reject(error);
    });
  });
}

export default {
  get,
  post,
  put,
  delet,
  fileUpload,
  exportFile
}